﻿using System;
using System.Data.Entity.Validation;
using System.Web.Mvc;
using Api.Common;

namespace AppManager.Background
{
    public class BaseController : Controller
    {
        public int userId { get; set; }
        /// <summary>
        ///     ModelError
        /// </summary>
        public const string Error = "ModelError";

        #region _Tip页面显示消息
        /// <summary>
        /// 在_Tip页面中添加错误信息
        /// </summary>
        /// <param name="value"></param>
        /// <param name="key"></param>
        public void AddErrorInfo(string value = "", string key = Error)
        {
            ViewBag.HasModelError = true;
            if (!string.IsNullOrEmpty(value))//不传递value时一般是直接显示ModelState中原有的错误信息，而没有其他的附加信息
            {
                ModelState.AddModelError(Error, value);
            }
        }
        /// <summary>
        /// 在_Tip页面中添加成功信息的显示
        /// </summary>
        /// <param name="message"></param>
        public void AddSuccessInfo(string message)
        {
            ViewBag.SuccessInfo = message;
        }
        public void AddScript(string script)
        {
            ViewBag.ViewScript = script;
        }
        public void AddScript_Redirect(string url)
        {
            AddScript("location.href=" + url);
        }
        /// <summary>
        /// 添加ef验证错误信息
        /// </summary>
        /// <param name="ex"></param>
        public void AddDbValidateionError(DbEntityValidationException ex)
        {
            AddErrorInfo("有必填项未填写");
            if (ex.EntityValidationErrors != null)
            {
                foreach (var item in ex.EntityValidationErrors)
                {
                    if (item.ValidationErrors != null)
                    {
                        foreach (var error in item.ValidationErrors)
                        {
                            AddErrorInfo(error.ErrorMessage, error.PropertyName);
                        }
                    }
                }
            }
        }
        #endregion

        #region 封装Json返回
        public JsonResult ResponseJsonFail(string msg)
        {
            AjaxResult result = new AjaxResult { status = false, msg = msg };
            return Json(result);
        }
        public JsonResult ResponseJsonFail(AjaxResult result)
        {
            if (result == null)
                throw new ArgumentException("result is null");

            result.status = false;
            return Json(result);
        }

        public JsonResult ResponseJsonSuccess(AjaxResult result = null)
        {
            if (result == null)
            {
                result = new AjaxResult { status = true };
            }
            return Json(result);
        }
        #endregion
    }
}